<template>
  <div class="update-avatar">
    <img id='image' :src="image" />
    <div class="toolbar">
      <span @click="$emit('close')">取消</span>
      <span @click='onConfirm'>完成</span>
    </div>
  </div>
</template>

<script>
import { saveAvatar } from '@/api/user.js'
// cropperjs 裁剪图片的插件
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
export default {
  data () {
    return {}
  },
  props: {
    // 父传子选中的图片地址
    image: {
      type: String,
      required: true
    }
  },
  methods: {
    onConfirm () {
      this.$toast.loading({
        message: '裁剪中...',
        forbidClick: true,
        duration: 0
      })
      // 方法一:服务器裁剪
      // console.log(this.cropper.getData())
      // 方法二:客户端裁剪
      this.cropper.getCroppedCanvas().toBlob(async blob => {
        // 创建表单数据
        const fromData = new FormData()
        fromData.append('phopo', blob)
        try {
          const { data: res } = await saveAvatar(fromData)
          this.$toast('裁剪成功')
          this.$emit('close')
          this.$emit('onUploadSuccess', res.data.phopo)
        } catch (err) {
          this.$toast('裁剪失败')
        }
      })
    }
  },
  computed: {},
  watch: {},
  filters: {},
  components: {},
  created () { },
  mounted () {
    // 使用cropperjs 进行裁剪
    const image = document.getElementById('image')
    this.cropper = new Cropper(image, {
      // 设置裁剪框大小
      aspectRatio: 1,
      // 去除裁剪背景
      background: false,
      // 图片只能在裁剪位置移动
      viewMode: 1,
      // 画布和图片都可以移动
      dragMode: 'move',
      // 自动调整裁剪图片
      autoCropArea: 1,
      // 禁止裁剪区移动
      cropBoxMovable: false,
      // 禁止裁剪区缩放
      cropBoxResizable: false
    })
  }
}
</script>

<style scoped lang='less'>
.update-avatar {
  background: #000;
  width: 100%;
  height: 100%;
  .toolbar {
    position: fixed;
    bottom: 10px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    font-size: 28px;
    color: #fff;
    padding: 0 15px;
    box-sizing: border-box;
  }
}
</style>
